layui.use(['form','layer','element'],function(){
	var form = layui.form,layer = layui.layer,element = layui.element;
	
	var isParaShow = true;
	form.on('select(para-from)',function(){
		var paraFrom = $("#paraFrom").val();
		if(paraFrom == 1){
			$("#para-div").show();
			$("#dataset-div").hide();
			initPara();
			isParaShow = true;
		}
		if(paraFrom == 2){
			$("#para-div").hide();
			$("#dataset-div").show();
			isParaShow = false;
			initDataset();
		}
			
	});
	
	
	form.on('select(dataset-sel)',function(data){
		var val = data.value;
		initParaByDataset(val);
	});
	
	form.on('select(oldpara-sel)',function(data){
		var val = data.value;
		showOldPara(val);
	});
	
	
	function showOldPara(val){
		if(isBlank(val))
			return false;
		ajaxPost("../para/getParaDataByParaId",{"paraId":val},
				function(data){
			      var list = data.data;
			      initOldParaData(list);
			
				},function(data){
					parent.layer.alert(data.errorMsg, {
    					icon: 5,
    					title: "错误"
    					});
				})
	}
	
	
	function initOldParaData(list){
		for(var i = 0 ;i < list.length;i++){
			var paraData = list[i];
			
			var cloneObj = $("#cloneObj").clone();
			$("#oldPara").append(cloneObj);
			cloneObj.find("label").html("");
			cloneObj.find("input[name='paraData']").val(paraData.paraData);
			if(i > 0)
			cloneObj.find("div:eq(1)").append('<i class="layui-icon" style="cursor:pointer" onclick="delParaVal(this)">&#x1006;</i>');
		}
	}
	
	$("#save-btn").on('click',function(){
		if(isParaShow)
			save();
		else 
		   setDataset();
		
	});
	initPara();
	function initPara(){
		var operateRule = $("#operateRule").val();
		if(!isBlank(operateRule))
			$("input[name='operateReadRule'][value='"+operateRule+"']").attr("checked",true); 
		var operateData = $("#operateData").val();
		var data = [];
		parent.$("input[name='operateData']").each(function(){
			var paraId = parent.$(this).val();
			if(!isBlank(paraId))
			data.push(paraId)
		});
		if(data.length == 0)
			return false;
		ajaxPost('../para/getOperSelData',{"paraIds":data.join(",")},
				function(data){
                    var para = data.data;
                    var content = [];
                    for(var i = 0 ;i < para.length;i++){
                    	if(!isBlank(operateData) && operateData == para[i].id)
                    		content.push("<option value='"+para[i].id+"' selected>"+para[i].paraName+"</option>");
                    	else
                    		content.push("<option value='"+para[i].id+"'>"+para[i].paraName+"</option>");
                    }
					$("#sel>option:gt(0)").remove();
					$("#sel").append(content.join(""));
					form.render("select");
					if(!isBlank(operateData))
						showOldPara(operateData);
			   
				},
				function(data){
					parent.layer.alert(data.errorMsg, {
    					icon: 5,
    					title: "错误"
    					});
				});
	}
	
	
	function initDataset(){
		var operateRule = $("#operateRule").val();
		if(!isBlank(operateRule))
			$("input[name='operateReadRule'][value='"+operateRule+"']").attr("checked",true); 
		var data = {};
		ajaxPost('../dataset/getDatasetByParaType',data,
				function(data){
                    var para = data.data;
                    var content = [];
                    for(var i = 0 ;i < para.length;i++){
                    	content.push("<option value='"+para[i].id+"'>"+para[i].datasetName+"</option>");
                    }
					$("#dataset-sel>option:gt(1)").remove();
					$("#dataset-sel").append(content.join(""));
					form.render("select");
			   
				},
				function(data){
					parent.layer.alert(data.errorMsg, {
    					icon: 5,
    					title: "错误"
    					});
				});
	}
	
	
	
	function initParaByDataset(val){
		var data = {'datasetId':val};
		ajaxPost('../para/getParaByDataset',data,
				function(data){
					var paraDatas = data.data;
					$("#dataset-para").empty();
					for(var i = 0 ;i < paraDatas.length;i++){
						var para = paraDatas[i];
						var ht = '<div class="layui-colla-item">'+
									'<div class="layui-colla-title"> <input type="radio" name="dataset" value="'+para.id+'" title="'+para.paraName+'"></input></div>'+
									'<div class="layui-colla-content">';
						var paraData = para.paraDataList;
						for(var j = 0 ;j < paraData.length;j++){
							var paraVal = paraData[j];
							ht += '<div style="text-align:left;font-size:14px;line-height:14px;margin-bottom:10px;s">'+paraVal.paraData+'</div>';
						}
						ht +='</div></div>'
						$("#dataset-para").append(ht);
					}
					element.init();
					form.render('radio');

				},
				function(data){
					parent.layer.alert(data.errorMsg, {
    					icon: 5,
    					title: "错误"
    					});
				});
		
	}
	
	function addParaVal(obj){
		var cloneObj = $("#cloneObj").clone();
		$(obj).closest("div[name='paradiv']").append(cloneObj);
		cloneObj.find("label").html("");
		cloneObj.find("input[name='paraData']").val("");
		cloneObj.find("div:eq(1)").append('<i class="layui-icon" style="cursor:pointer" onclick="delParaVal(this)">&#x1006;</i>');
	}
	window.addParaVal = addParaVal;
	
	function delParaVal(obj){
		$(obj).parent("div").parent("div").remove();
	}
	window.delParaVal = delParaVal;
	
	
	function save(){
		var val = $("#sel").val();
		var newpara = $("#paraName").val();
		
		if(!isBlank(val) && !isBlank(newpara)){
			var text = $("#sel>option[value="+val+"]").text();
			layer.confirm('您既选择了已有数据['+text+']，又新增了数据['+newpara+']，请选择其一', {
				  btn: ['新增','已有'] //按钮
				}, function(){
				   addnew();
				}, function(){
				   addold();
				});
		}else if(!isBlank(val))
			addold();
		else if(!isBlank(newpara))
			addnew();
	}
	
	
	function addnew(){
		var newpara = $("#paraName").val();
		var operateRule = $("input[name='operateReadRule']:checked").val();
		if(isBlank(operateRule))
			operateRule = "";
		var reuseType = $("input[name='reuseType']:checked").val();
		if(isBlank(reuseType))
			reuseType = 1;
		var newparaVal = [];
		var isValidated = true;
		$("#newpara").find("input[name='paraData']").each(function(index){
			var val = $(this).val();
			if(isBlank(val)){
				layer.tips("请输入变量值",$(this),{
	      			  tips: [1, '#FF0000'],
	      			  time: 3000
	      			});
				isValidated = false;
				return false;
			}
		newparaVal.push({'paraData':val,'dataOrder':(index+1),'useType':2});
		});
		
		if(!isValidated)
			return false;
		
		var data = {'paraJson':JSON.stringify({'paraName':newpara,'reuseType':reuseType}),
				'paraDataJson':JSON.stringify(newparaVal)};
		ajaxPost('../para/saveParaData',data,
					function(data){
						var index = $("#index").val();
						if(isBlank(index)){
							layer.alert("页面传值失败，请重新打开页面", {
								icon: 5,
								title: "错误"
								});
							return false;
						}
						var selectType = $("#selectType").val();
						if(selectType == 2){
							parent.$("#dg>tr:eq("+index+")").find("input[name='operateData']").val(data.data.id);
							parent.$("#dg>tr:eq("+index+")").find("input[name='data-input']").val(data.data.paraName);
							parent.$("#dg>tr:eq("+index+")").find("input[name='operateRule']").val(operateRule);
						}else{
							parent.$("#dg>tr:eq("+index+")").find("input[name='outputData']").val(data.data.id);
							parent.$("#dg>tr:eq("+index+")").find("input[name='data-output']").val(data.data.paraName);
						}
						var idx = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
						parent.layer.close(idx);
			     
					},
					function(data){
						layer.alert(data.errorMsg, {
							icon: 5,
							title: "错误"
							});
						return false;
					});
	}
	
	function addold(){
		var id = $("#sel").val();
		var text = $("#sel>option[value="+id+"]").text();
		var operateRule = $("input[name='operateReadRule']:checked").val();
		var index = $("#index").val();
		var selectType = $("#selectType").val();
		if(isBlank(index)){
			layer.alert("页面传值失败，请重新打开页面", {
				icon: 5,
				title: "错误"
				});
			return false;
		}
		var oldParaVal = [];
		var isValidated = true;
		$("#oldPara").find("input[name='paraData']").each(function(index){
			var val = $(this).val();
			if(isBlank(val)){
				layer.tips("请输入变量值",$(this),{
	      			  tips: [1, '#FF0000'],
	      			  time: 3000
	      			});
				isValidated = false;
				return false;
			}
		oldParaVal.push({'paraData':val,'dataOrder':(index+1),'useType':2});
		});
		
		if(!isValidated)
			return false;
		
		ajaxPost("../para/changeParaData",{"paraId":id,"paraData":JSON.stringify(oldParaVal)},
			function(data){
			if(selectType == 2){
				parent.$("#dg>tr:eq("+index+")").find("input[name='operateData']").val(id);
				parent.$("#dg>tr:eq("+index+")").find("input[name='data-input']").val(text);
				parent.$("#dg>tr:eq("+index+")").find("input[name='operateRule']").val(operateRule);
			}else{
				parent.$("#dg>tr:eq("+index+")").find("input[name='outputData']").val(id);
				parent.$("#dg>tr:eq("+index+")").find("input[name='data-output']").val(text);
			}
			var idx = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
			parent.layer.close(idx);
		},
			function(data){
				layer.alert(data.errorMsg, {
					icon: 5,
					title: "错误"
					});
				return false;
			});
	}
	
	
	function setDataset(){
		var id = $("input[name = 'dataset']:checked").val();
		if(isBlank(id)){
			layer.alert("请选择变量参数", {
				icon: 5,
				title: "错误"
				});
			return false;
		}
		var text =$("input[name = 'dataset']:checked").attr('title');
		var operateRule = $("input[name='operateReadRule']:checked").val();
		var index = $("#index").val();
		var selectType = $("#selectType").val();
		if(isBlank(index)){
			layer.alert("页面传值失败，请重新打开页面", {
				icon: 5,
				title: "错误"
				});
			return false;
		}
		
		if(selectType == 2){
			parent.$("#dg>tr:eq("+index+")").find("input[name='operateData']").val(id);
			parent.$("#dg>tr:eq("+index+")").find("input[name='data-input']").val(text);
			parent.$("#dg>tr:eq("+index+")").find("input[name='operateRule']").val(operateRule);
		}else{
			parent.$("#dg>tr:eq("+index+")").find("input[name='outputData']").val(id);
			parent.$("#dg>tr:eq("+index+")").find("input[name='data-output']").val(text);
		}
		var idx = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
		parent.layer.close(idx);
	}
});